
import * as tfvis from "@tensorflow/tfjs-vis";
import * as tf from "@tensorflow/tfjs";
import { getData } from "./data";
import { useEffect, useRef } from "react";
export default function () {
    const formDom = useRef();
    const modelRef = useRef();
    async function start () {
        const data = getData(400);
        tfvis.render.scatterplot(
            { name: "XOR训练数据" },
            {
                values: [
                    data.filter(p => p.label === 1),
                    data.filter(p => p.label === 0)
                ]
            }
        )
        const model = tf.sequential();
        model.add(tf.layers.dense({
            units: 4,
            inputShape: [2],
            activation: "relu"
        }));
        model.add(tf.layers.dense({
            units: 1,
            activation: "sigmoid"
        }))
        model.compile({
            loss: tf.losses.logLoss,
            optimizer: tf.train.adam(0.1)
        })
        const inputs = tf.tensor(data.map(p => [p.x, p.y]));
        const labels = tf.tensor(data.map(p => p.label));
        await model.fit(inputs, labels, {
            epochs: 10,
            callbacks: tfvis.show.fitCallbacks(
                {name: "训练效果"},
                ['loss']
            )
        })
        modelRef.current = model;
    }
    useEffect(() => {
        start();
    }, [])
    function predict() {
        const form = formDom.current;
        const model = modelRef.current;
        const pred = model.predict(tf.tensor([[form.x.value * 1, form.y.value * 1]]));
        console.log("预测结果:" + pred.dataSync()[0]);
    }
    return <div>
        <form ref={formDom}>
            x: <input type="text" name="x" />
            y: <input type="text" name="y" />
        </form>
        <button onClick={predict} >预测</button>
    </div>
}